const {getList,getDetail,newBlog,updateBlog,delBlog} = require("../controller/blog");
const { SuccessModel,ErrorModel} = require("../model/resmodel");
//统一的登陆验证函数
const loginCheck = (req) =>{
    if(!req.session.username){
        return Promise.resolve(
            new ErrorModel('尚未登陆')
        )
    }
}
const handleBlogRouter  = (req,res)=>{
    const method = req.method;
    const id = req.query.id || "";
    
    //获取博客列表
    if(method === "GET" && req.path === '/api/blog/list'){
        let author = req.query.author || "";
        const keyword = req.query.keyword || "";
        // const listData = getList(author,keyword);
        // return new SuccessModel(listData);
        if(req.query.isadmin){
            //管理员界面
            const loginCheckResult = loginCheck(req);
            if(loginCheckResult){
                //未登陆
                return loginCheckResult;
            }
            //强制查询自己的博客
            author = req.session.username;
        }
        const result = getList(author,keyword);
        
        return result.then(listData=>{
            
                return new SuccessModel(listData);
        })
        
        
    }
    //获取博客详情
    if(method === "GET" && req.path === "/api/blog/detail"){
        
        const result = getDetail(id);
        return result.then(data=>{
            return new SuccessModel(data);
        })
    }
    //新增博客
    if(method === "POST" && req.path === "/api/blog/new"){
        const loginCheckResult = loginCheck(req);
        
        if(loginCheckResult){
            //未登陆
            return loginCheckResult;
        }
        
        req.body.author = req.session.username;
        req.body.createtime = new Date().getTime();
        // const blogData = req.body;
        const data = newBlog(req.body);
        return data.then(result=>{
            return new SuccessModel(result);
        })
    }
    //更新博客
    if(method === "POST" && req.path === "/api/blog/update"){
        const loginCheckResult = loginCheck(req);
        if(loginCheckResult){
            //未登陆
            return loginCheckResult;
        }
        const result = updateBlog(id,req.body);
        if(result){
            return result.then(data=>{
                return new SuccessModel(data);
            })
        }else{
            return new ErrorModel("更新博客失败");
        }
    }
    //删除博客
    if(method === "POST" && req.path === "/api/blog/del"){
        const loginCheckResult = loginCheck(req);
        
        if(loginCheckResult){
            //未登陆
            return loginCheckResult;
        }
        const author = req.session.username;
        
        const result = delBlog(req.body.id,author);
        
        if(result){
            return result.then((data)=>{
                
                return new SuccessModel(data);
            })
            
        }else{
            return new ErrorModel("更新失败");
        }
    }
}
module.exports = handleBlogRouter;